//
//  WBBaseViewController.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/5/9.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import UIKit

class WBBaseViewController: UIViewController {
    
    /// 默认的表格
    var tableView :UITableView?
    
    /// 下拉刷新控件
    var refreshControl : UIRefreshControl?
    
    /// 上拉刷新标记
    var isPullup = false
    
    /// 访客视图数据字典
    var visitorInfoDictionary:[String : String]?
    
    /// 自定义导航栏
    lazy var naviBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64))
    
    /// 自定义导航栏按钮
    lazy var naviItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        automaticallyAdjustsScrollViewInsets = false
        
        setupUI()
        
        //如果没有登录，就不加载数据
        (WBNetworkManager.shared.userLogon) ? loadData() : ()
        
        //注册登录成功通知
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(loginSuccess),
                                               name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification),
                                               object: nil)
        
    }
    
    deinit {
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 设置控制器标题
    override var title: String? {
        
        didSet {
            
            naviItem.title = title
        }
    }
    
    /// 返回按钮
    func back() {
        
        _ = navigationController?.popViewController(animated: true);
    }
    
    /// 加载数据源
    func loadData() {
        
        //结束刷新控件
        refreshControl?.endRefreshing()
    }
}

// MARK: - 访客视图的监听事件
extension WBBaseViewController{
    
    ///登录成功监听事件
    @objc fileprivate func loginSuccess(noti:Notification) {
        
        print("登录成功")
        
        view = nil
        
        //清除导航栏
        naviItem.rightBarButtonItem = nil
        
        naviItem.leftBarButtonItem = nil
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
        
    }
    
    /// 登录按钮监听事件
    @objc fileprivate func login() {
        
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil, userInfo: nil)
    }
    
    /// 注册按钮监听事件
    // FIXME:未编写
    @objc fileprivate func registe() {
        print("用户注册")
    }
}

// MARK: - 设置UI
extension WBBaseViewController{
    
    /// 设置UI
    func setupUI() {
        
        //设置随机色
        view.backgroundColor = UIColor().randomColor
        
        setupNavigationBar()
        
        //未登录，就显示访客视图，登录显示表格视图
        (WBNetworkManager.shared.userLogon) ? setupTableView() : setupVisitorView()
    }
    
    /// 设置访客视图
    fileprivate func setupVisitorView() {
        
        let visitorView = WBVisitorView(frame: view.bounds)
        
        view.insertSubview(visitorView, belowSubview: naviBar)
        
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        
        visitorView.registerButton.addTarget(self, action: #selector(registe), for: .touchUpInside)
        
        visitorView.visitorInfo = visitorInfoDictionary
        
    }
    
    /// 设置表格视图
    func setupTableView() {
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        
        view.insertSubview(tableView!, belowSubview: naviBar)
        
        tableView?.contentInset = UIEdgeInsets(top: naviBar.height, left: 0, bottom:tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        tableView?.delegate = self
        
        tableView?.dataSource = self
        
        //添加系统的下拉刷新控件
        refreshControl = UIRefreshControl()
        
        tableView?.addSubview(refreshControl!)
        
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
    
    /// 设置导航条
    private func setupNavigationBar() {
        
        //添加导航栏
        naviBar.items = [naviItem]
        
        naviBar.barTintColor = UIColor(hexColor: "f6f6f6")
        
        naviBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.darkGray];
        
        if !WBNetworkManager.shared.userLogon {
            
            naviItem.leftBarButtonItem = UIBarButtonItem(title: "登录", target: self, action: #selector(login))
            
            naviItem.rightBarButtonItem = UIBarButtonItem(title: "注册", target: self, action: #selector(registe))
        }
        
        view.addSubview(naviBar)
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource
extension WBBaseViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        return UITableViewCell()
    }
    
    /// 在显示到最后一行时，上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let row = indexPath.row
        
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0 {
            
            return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        
        if row == (count - 1) && !isPullup {
            
            print("上拉刷新")
            
            isPullup = true
            
            loadData()
        }
    }
}
